package com.xl.utils.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author xionglin
 * @date 2019/9/5 22:39
 * @Description spring上下文及bean的获取工具类
 */
@Slf4j
@Component
public class SpringBeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtils.applicationContext = applicationContext;
        log.info("--------->>ApplicationContext配置成功,applicationContext对象："+ SpringBeanUtils.applicationContext);
    }

    /**通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }

    /**
     * 通过name获取 Bean
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        assertApplicationContext();
        return applicationContext.getBean(beanName);
    }

    /**
     * 通过class获取Bean.
     * @param requiredType
     * @return
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 空值检查
     */
    private static void assertApplicationContext() {
        if (applicationContext == null) {
            log.error("---------->>applicaitonContext属性为null,请检查是否注入了SpringUtils!");
            throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringUtils!");
        }
    }
}
